package com.jfs.strategy.message.impl;

import com.jfs.enums.MessageEnum;
import com.jfs.envent.EventPublisher;
import com.jfs.envent.entity.MessageKeepAliveEntity;
import com.jfs.observer.request.abstracts.AbstractProcessor;
import com.jfs.strategy.message.MessageStrategy;
import com.jfs.utils.XstreamUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.sip.RequestEvent;


/**
 * @Description 心跳处理策略
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/7/22
 */
@Component
@Slf4j
@AllArgsConstructor
public class MessageKeepAliveStrategy implements MessageStrategy {
    private final EventPublisher eventPublisher;

    @Override
    public boolean support(String content) {
        return content.contains(MessageEnum.MESSAGE_KEEP_ALIVE.getCmd());
    }

    @Override
    public void processor(String content, AbstractProcessor abstractProcessor, RequestEvent requestEvent) {
        try {
            MessageKeepAliveEntity messageKeepAliveEntity = XstreamUtil.toBean(MessageKeepAliveEntity.class, content);
            assert messageKeepAliveEntity != null;
            messageKeepAliveEntity.setRequestEvent(requestEvent);
            messageKeepAliveEntity.setIp(abstractProcessor.getIpByRequest(requestEvent));
            messageKeepAliveEntity.setPort(abstractProcessor.getPortFromRequest(requestEvent));
            messageKeepAliveEntity.setTransport(abstractProcessor.getTransactionFormRequest(requestEvent));
            //发布心跳事件
            eventPublisher.publish(messageKeepAliveEntity);
            //回复心跳
            abstractProcessor.doSuccess(requestEvent);
        } catch (Exception e) {
            log.info("处理心跳请求发生异常:{}", e.getMessage());
            e.printStackTrace();
        }
    }
}
